import axios from 'axios'
// import store from './store/store'
// import * as types from './store/types'
// import router from './router'

axios.defaults.baseURL = BASE_URL // 开发环境
// axios 配置
axios.defaults.timeout = 500000
// axios.defaults.baseURL = '/' // 开发环境
// axios.defaults.baseURL = 'https://office.ptxinke.com:10444/ptxinke-system/' // 正式环境

// http request 拦截器
axios.interceptors.request.use(
  config => {
  // 允许携带cookie ,这个是解决跨域产生的相关问题
    config.withCredentials = true
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = token
    }
    if (config.method === 'post') {
      config.data = {
        ...config.data,
        _t: Date.parse(new Date()) / 1000
      }
    } else if (config.method === 'get') {
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params
      }
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    if (response.status === 403 || response.data === 401) {
      // 401 清除token信息并跳转到登录页面
      // store.commit(types.LOGOUT)
      console.log('未授权 清除token信息并跳转到登录页面')

      // 只有在当前路由不是登录页面才跳转
      // router.currentRoute.name !== 'login' &&
      // router.replace({
      //   name: 'login',
      //   query: { redirect: router.currentRoute.path }
      // })
    }
    return response
  },
  error => {
    console.log('403错误提示:')
    console.log(error.response)
    if (error.response) {
      console.log('error.response.status:' + error.response.status)
      switch (error.response.status) {
        case 403:
          // 返回 403 清除token信息并跳转到登录页面
          // store.commit(types.LOGOUT)
          // router.currentRoute.name !== 'login' &&
          // router.replace({
          //   name: 'login',
          //   query: { redirect: router.currentRoute.path }
          // })
      }
    }
    console.log('http response 拦截器错误' + JSON.stringify(error)) // console : Error: Request failed with status code 402
    return Promise.reject(error.response)
  }
)

export default axios
